﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1" name="viewport">
    <title>HTML5聊天窗口界面</title>
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600" rel="stylesheet">
    <link href="css/reset.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

</head>
<body>

<div class="wrapper" id="app">

    <div :class="['popup', { 'active': popupVisible }]">
        <div class="popup-content">{{ popupMessage }}</div>
    </div>
    <div class="container">
        <div class="left">
            <div class="top">
                <input placeholder="Search" type="text"/>
                <a class="search" href="javascript:"></a>
            </div>
            <ul class="people" v-for="user in userList">
                <li @click="changeMessageObject(user.id, user.type)" class="person">
                    <img :src="'img/'+user.img" alt=""/>
                    <span class="name">{{user.name}}</span>
                    <span class="time">{{user.time}}</span>
                    <span class="preview">{{user.preview}}</span>
                </li>
            </ul>
        </div>
        <div class="right">
            <div class="top"><span>To: <span class="name">{{currentSendMessageUserName}}</span></span></div>
            <div class="chat">
                <div class="conversation-start">
                    <span>Today, 6:48 AM</span>
                </div>
                <div v-for="chat in chatList">
                    <div class="bubble me" v-if="chat.type===1">
                        {{chat.message}}
                    </div>
                    <div class="bubble you" v-if="chat.type===2">
                        {{chat.message}}
                    </div>
                </div>
            </div>
            <div class="write">
                <a class="write-link attach" href="javascript:"></a>
                <input @keyup.enter="send()" type="text" v-model="sendMessage"/>
                <a class="write-link smiley" href="javascript:"></a>
                <a @click="send()" class="write-link send" href="javascript:"></a>
            </div>
        </div>
    </div>
</div>

<script src="js/vue.js"></script>
<script src="js/axios-0.18.0.js"></script>
<script>
    let ws;
    new Vue({
        el: "#app",
        data() {
            return {
                sendMessage: '',
                userList: [],
                currentSendMessageUserId: '',
                currentSendMessageUserName: '',
                currentSendMessageUserType: '',
                userId: 0,
                chatList: [],

                localChatHistory: [],

                // 系统消息提示
                popupVisible: false,
                popupMessage: ''
            }
        },
        created() {
            this.userId = parseInt(new URLSearchParams(window.location.search).get("token"));
            this.getUserList();
            // "{\"nsrsbh\":\"91110108MA01F6BKX8\",\"cxyfs\":\"36\",\"dsfcjbm\":\"2023060291615\"}"

            let sendMessage = {
                nsrsbh: '91110108MA01F6BKX8',
                cxyfs: '36',
                dsfcjbm: '2023060291615'
            };
            console.log(JSON.stringify(sendMessage))
        },
        methods: {
            // 发型消息的按钮
            send() {
                this.personalMessage(1, this.sendMessage)
                this.wsSend()
                this.clearSendMessage()
            },
            // 清除聊天的对象
            clearSendMessage() {
                this.sendMessage = ''
            },
            // 消息增加到数组里面
            personalMessage(type, message) {
                this.chatList.push({
                    type: type,
                    message: message
                });
            },
            // 系统消息
            systemMessage(message) {
                this.popupMessage = message;
                this.popupVisible = true;
                setTimeout(() => {
                    this.popupVisible = false;
                }, 3000);
            },
            // 更变聊天对象
            changeMessageObject(id, type) {
                if (id === this.currentSendMessageUserId && type === this.currentSendMessageUserType) {
                    return;
                }
                this.saveChatRecord();

                let obj = this.userList.find(o => o.id === id && o.type === type)
                this.currentSendMessageUserId = obj.id
                this.currentSendMessageUserName = obj.name
                this.currentSendMessageUserType = obj.type;

                let chatObj = this.localChatHistory.find(o => o.id === id && o.type === type)
                if (chatObj === undefined) {
                    this.chatList = []
                } else {
                    this.chatList = chatObj.chatList
                }
            },
            // 保存当前的聊天记录
            saveChatRecord() {
                if (this.chatList.length === 0) {
                    return;
                }
                let arr = this.localChatHistory;
                if (arr.some(o => o.id === this.currentSendMessageUserId && o.type === this.currentSendMessageUserType)) {
                    let chatObj = this.localChatHistory.find(o => o.id === this.currentSendMessageUserId && o.type === this.currentSendMessageUserType)
                    chatObj.chatList = this.chatList
                } else {
                    arr.push({
                        id: this.currentSendMessageUserId,
                        type: this.currentSendMessageUserType,
                        chatList: this.chatList
                    });
                }
            },

            // ws
            wsInit() {
                //创建webSocket对象
                ws = new WebSocket("ws://localhost:8080/websocket/" + this.userId);

                // 给ws绑定事件
                ws.onopen = this.wsOnOpen;
                ws.onmessage = this.wsOnMessage;
                ws.onclose = this.wsOnClose;
            },
            wsSend() {
                if (this.currentSendMessageUserType === 2) {
                    let sendMessage = {
                        sendId: this.userId,
                        type: this.currentSendMessageUserType,
                        message: this.sendMessage,
                        groupId: this.currentSendMessageUserId
                    };
                    ws.send(JSON.stringify(sendMessage));
                } else {
                    let sendMessage = {
                        sendId: this.userId,
                        type: this.currentSendMessageUserType,
                        message: this.sendMessage,
                        receiveId: this.currentSendMessageUserId
                    };
                    ws.send(JSON.stringify(sendMessage));
                }
            },
            wsOnOpen() {
                // 通知好友上线
                this.friendOnline();
            },
            wsOnClose() {
            },
            wsOnMessage(res) {
                console.log(res.data)
                let vo = JSON.parse(res.data)
                if (vo.type === 3) {
                    this.systemMessage(vo.message);
                } else {
                    if ((vo.sendId === this.currentSendMessageUserId || vo.groupId === this.currentSendMessageUserId) && vo.type === this.currentSendMessageUserType) {
                        this.personalMessage(2, vo.message);
                    } else {
                        // todo 逻辑有问题
                        let arr = this.localChatHistory;
                        let chat = [{
                            type: 2,
                            message: vo.message
                        }]
                        // if (vo.type === 2) { // 群聊
                            if (arr.some(o => o.id === this.currentSendMessageUserId && o.type === this.currentSendMessageUserType)) {
                                let chatObj = this.localChatHistory.find(o => o.id === this.currentSendMessageUserId && o.type === this.currentSendMessageUserType)
                                chatObj.chatList.push(chat)
                            } else {
                                arr.push({
                                    id: this.currentSendMessageUserId,
                                    type: this.currentSendMessageUserType,
                                    chatList: chat
                                });
                            }
                        // } else { // 个人
                        //     if (arr.some(o => o.id === this.currentSendMessageUserId && o.type === this.currentSendMessageUserType)) {
                        //         let chatObj = this.localChatHistory.find(o => o.id === this.currentSendMessageUserId && o.type === this.currentSendMessageUserType)
                        //         chatObj.chatList = this.chatList
                        //     } else {
                        //         arr.push({
                        //             id: this.currentSendMessageUserId,
                        //             type: this.currentSendMessageUserType,
                        //             chatList: this.chatList
                        //         });
                        //     }
                        // }



                        // if (arr.some(o => o.id === vo.sendId && o.type === vo.type)) {
                        //     for (let i = 0; i < arr.length; i++) {
                        //         if (arr[i].id === this.userId) {
                        //             arr[i].chatList = this.chatList;
                        //             break; // 如果只想替换第一个符合条件的元素，则添加break语句结束循环
                        //         }
                        //     }
                        // } else { // 添加记录
                        //     arr.push({
                        //         id: vo.type === 2 ? vo.receiveId : vo.groupId,
                        //         type: vo.type,
                        //         chatList: chat
                        //     });
                        // }
                        // console.log(arr)
                    }
                }
            },

            // 后端接口
            getUserList() {
                axios.get("/user/list", {
                    headers: {token: this.userId}
                }).then(res => {
                    this.userList = res.data.data;
                    this.currentSendMessageUserId = this.userList[0].id;
                    this.currentSendMessageUserName = this.userList[0].name;
                    this.currentSendMessageUserType = this.userList[0].type;

                    this.wsInit();
                });

            },
            friendOnline() {
                axios.get("/friend/online", {
                    headers: {token: this.userId}
                });
            },

        }
    });
</script>


</body>
</html>